package com.example.zookeeper.demo;

import com.example.zookeeper.core.ZkCore;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.springframework.stereotype.Component;

@Component
public class ZkNodeDemo
{
    private final ZkCore zkCore;

    public ZkNodeDemo(ZkCore zkCore)
    {
        this.zkCore = zkCore;
    }

    /**
     * 创建一个临时节点
     * 获取节点的值并且打印
     */
    public void start()
    {
        try
        {
            if (zkCore.exist("/test") == null)
            {
                zkCore.createNode("/test", "hello zookeeper".getBytes(), CreateMode.EPHEMERAL);
            }
            else
            {
                System.out.println("node /test has exist!");
            }
            String value = new String(zkCore.getValue("/test"));
            System.out.println("=======================>>>" + value);
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public void close()
    {
        try
        {
            zkCore.close();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
